/*
 * @Date: 2020-09-14 15:49:07
 * @LastEditors: 小枫
 * @LastEditTime: 2020-09-21 17:07:19
 * @FilePath: \feng-blog\app\controller\Tag.ts
 */
import { Controller } from 'egg';

export default class TagController extends Controller {
  public async index() {
    const { ctx } = this;
    try {
      const result = await ctx.service.tag.getAllTags();
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async create() {
    const { ctx } = this;
    const { tag, photoUrl } = ctx.request.body;
    try {
      const hasTag = await ctx.service.tag.getTagByName(tag);
      if (hasTag.length !== 0) {
        ctx.status = 403;
        ctx.body = {
          msg: '标签已存在',
        };
        return;
      }
      const result = await ctx.service.tag.insertTag({ tag, photoUrl });
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async update() {
    const { ctx } = this;
    let { tid } = ctx.params;
    tid = parseInt(tid);
    const { tag, photoUrl } = ctx.request.body;
    const tagObj = {
      tid,
      tag,
      photoUrl,
    };
    try {
      const result = await ctx.service.tag.updateTag(tagObj);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }

  public async delete() {
    const { ctx } = this;
    let { tid } = ctx.params;
    tid = parseInt(tid);
    try {
      const { listByTag } = await ctx.service.article.getArticleByTag(tid);
      if (listByTag.length > 0) {
        ctx.status = 405;
        ctx.body = {
          msg: '已使用，不允许删除',
        };
        return;
      }
      const result = await ctx.service.tag.deleteTag(tid);
      ctx.status = 200;
      ctx.body = {
        data: result,
      };
    } catch (error) {
      ctx.status = 502;
      ctx.body = {
        msg: error,
      };
    }
  }
}
